<script setup lang="ts">
import type {
  RolloutPlan,
  VersionRecord,
  VersionsFacet,
} from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  versions?: VersionsFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [versions: VersionsFacet];
}>();

// 响应式数据
const createVersionModalVisible = ref(false);
const rolloutModalVisible = ref(false);
const versionDetailModalVisible = ref(false);
const selectedVersion = ref<null | VersionRecord>(null);

// 表单数据
const versionForm = reactive({
  version: '',
  type: 'PATCH',
  changelog: '',
  releaseNotes: '',
  tags: [] as string[],
});

const rolloutForm = reactive({
  name: '',
  targetVersion: '',
  strategy: 'ALL_AT_ONCE',
  scheduledAt: null as any,
  description: '',
  config: {
    batchCount: 1,
    batchInterval: 5,
    healthCheckTimeout: 30,
  },
});

// 计算属性
const versions = computed(
  () =>
    props.versions || {
      current: 'v1.0.0',
      status: 'RELEASED',
      history: [],
      rollouts: [],
    },
);

const availableVersions = computed(
  () => versions.value.history?.filter((v) => v.status === 'DRAFT') || [],
);

// 方法
const getVersionStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'default',
    REVIEW: 'orange',
    RELEASED: 'green',
    DEPRECATED: 'red',
    RETIRED: 'gray',
  };
  return colorMap[status || ''] || 'default';
};

const getVersionStatusLabel = (status?: string) => {
  const labelMap: Record<string, string> = {
    DRAFT: '草稿',
    REVIEW: '评审中',
    RELEASED: '已发布',
    DEPRECATED: '已废弃',
    RETIRED: '已退役',
  };
  return labelMap[status || ''] || status || '未知';
};

const getVersionTimelineColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'gray',
    REVIEW: 'orange',
    RELEASED: 'green',
    DEPRECATED: 'red',
    RETIRED: 'gray',
  };
  return colorMap[status || ''] || 'blue';
};

const getRolloutStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'orange',
    IN_PROGRESS: 'blue',
    COMPLETED: 'green',
    FAILED: 'red',
    PAUSED: 'gray',
  };
  return colorMap[status || ''] || 'default';
};

const getRolloutStatusLabel = (status?: string) => {
  const labelMap: Record<string, string> = {
    PENDING: '待执行',
    IN_PROGRESS: '执行中',
    COMPLETED: '已完成',
    FAILED: '失败',
    PAUSED: '已暂停',
  };
  return labelMap[status || ''] || status || '未知';
};

const getRolloutStrategyLabel = (strategy?: string) => {
  const labelMap: Record<string, string> = {
    ALL_AT_ONCE: '全量发布',
    CANARY: '金丝雀发布',
    BLUE_GREEN: '蓝绿发布',
    ROLLING: '滚动发布',
  };
  return labelMap[strategy || ''] || strategy || '未知';
};

const formatDate = (date?: string) => {
  if (!date) return '未设置';
  return new Date(date).toLocaleString('zh-CN');
};

// 版本管理方法
const showCreateVersionModal = () => {
  resetVersionForm();
  createVersionModalVisible.value = true;
};

const createVersion = () => {
  if (!versionForm.version || !versionForm.changelog) {
    message.error('请填写版本号和变更说明');
    return;
  }

  const newVersion: VersionRecord = {
    version: versionForm.version,
    status: 'DRAFT',
    changelog: versionForm.changelog,
    releaseNotes: versionForm.releaseNotes,
    tags: versionForm.tags,
    createdAt: new Date().toISOString(),
    createdBy: 'current-user',
  };

  const currentHistory = versions.value.history || [];
  const newHistory = [...currentHistory, newVersion];

  emit('update', { ...versions.value, history: newHistory });
  message.success('版本创建成功');
  createVersionModalVisible.value = false;
  resetVersionForm();
};

const cancelCreateVersion = () => {
  createVersionModalVisible.value = false;
  resetVersionForm();
};

const resetVersionForm = () => {
  versionForm.version = '';
  versionForm.type = 'PATCH';
  versionForm.changelog = '';
  versionForm.releaseNotes = '';
  versionForm.tags = [];
};

const rollbackToVersion = (version: string) => {
  message.info(`回滚到版本: ${version}`);
};

const viewVersionDetail = (version: VersionRecord) => {
  selectedVersion.value = version;
  versionDetailModalVisible.value = true;
};

// 发布计划方法
const showRolloutModal = () => {
  resetRolloutForm();
  rolloutModalVisible.value = true;
};

const createRollout = () => {
  if (!rolloutForm.name || !rolloutForm.targetVersion) {
    message.error('请填写计划名称和目标版本');
    return;
  }

  const newRollout: RolloutPlan = {
    id: `rollout_${Date.now()}`,
    name: rolloutForm.name,
    targetVersion: rolloutForm.targetVersion,
    strategy: rolloutForm.strategy,
    status: 'PENDING',
    progress: 0,
    scheduledAt: rolloutForm.scheduledAt?.toISOString(),
    description: rolloutForm.description,
    config: rolloutForm.config,
  };

  const currentRollouts = versions.value.rollouts || [];
  const newRollouts = [...currentRollouts, newRollout];

  emit('update', { ...versions.value, rollouts: newRollouts });
  message.success('发布计划创建成功');
  rolloutModalVisible.value = false;
  resetRolloutForm();
};

const cancelCreateRollout = () => {
  rolloutModalVisible.value = false;
  resetRolloutForm();
};

const resetRolloutForm = () => {
  rolloutForm.name = '';
  rolloutForm.targetVersion = '';
  rolloutForm.strategy = 'ALL_AT_ONCE';
  rolloutForm.scheduledAt = null;
  rolloutForm.description = '';
  rolloutForm.config = {
    batchCount: 1,
    batchInterval: 5,
    healthCheckTimeout: 30,
  };
};

const executeRollout = (rollout: RolloutPlan) => {
  message.info(`执行发布计划: ${rollout.name}`);
};

const pauseRollout = (rollout: RolloutPlan) => {
  message.info(`暂停发布计划: ${rollout.name}`);
};

const viewRolloutDetail = (rollout: RolloutPlan) => {
  message.info(`查看发布计划详情: ${rollout.name}`);
};

const deleteRollout = (rolloutId: string) => {
  const newRollouts =
    versions.value.rollouts?.filter((r) => r.id !== rolloutId) || [];
  emit('update', { ...versions.value, rollouts: newRollouts });
  message.success('发布计划删除成功');
};
</script>

<template>
  <div class="resource-versions">
    <!-- 版本管理头部 -->
    <div class="versions-header">
      <h3>版本管理</h3>
      <a-space>
        <a-button type="primary" @click="showCreateVersionModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          创建版本
        </a-button>
        <a-button @click="showRolloutModal">
          <template #icon>
            <IconifyIcon icon="ant-design:rocket-outlined" />
          </template>
          发布计划
        </a-button>
      </a-space>
    </div>

    <!-- 当前版本信息 -->
    <a-card title="当前版本" class="version-card">
      <a-descriptions :column="3">
        <a-descriptions-item label="版本号">
          <a-tag color="green" size="large">
            {{ versions?.current || 'v1.0.0' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getVersionStatusColor(versions?.status)" size="large">
            {{ getVersionStatusLabel(versions?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="发布时间">
          {{ formatDate(versions?.releasedAt) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <!-- 版本历史 -->
    <a-card title="版本历史" class="version-card">
      <div class="versions-section">
        <a-empty v-if="!versions?.history?.length" description="暂无版本历史" />

        <div v-else class="versions-list">
          <a-timeline>
            <a-timeline-item
              v-for="version in versions.history"
              :key="version.version"
              :color="getVersionTimelineColor(version.status)"
            >
              <template #dot>
                <a-tag
                  :color="getVersionStatusColor(version.status)"
                  size="small"
                >
                  {{ version.status }}
                </a-tag>
              </template>

              <div class="version-item">
                <div class="version-header">
                  <h4>{{ version.version }}</h4>
                  <a-space>
                    <a-tag :color="getVersionStatusColor(version.status)">
                      {{ getVersionStatusLabel(version.status) }}
                    </a-tag>
                    <a-button
                      v-if="version.status === 'RELEASED'"
                      type="link"
                      size="small"
                      @click="rollbackToVersion(version.version)"
                    >
                      回滚
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="viewVersionDetail(version)"
                    >
                      详情
                    </a-button>
                  </a-space>
                </div>

                <div class="version-info">
                  <p><strong>变更说明:</strong> {{ version.changelog }}</p>
                  <p>
                    <strong>创建时间:</strong>
                    {{ formatDate(version.createdAt) }}
                  </p>
                  <p><strong>创建人:</strong> {{ version.createdBy }}</p>
                  <p v-if="version.releasedAt">
                    <strong>发布时间:</strong>
                    {{ formatDate(version.releasedAt) }}
                  </p>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-card>

    <!-- 发布计划 -->
    <a-card title="发布计划" class="version-card">
      <div class="rollout-section">
        <a-empty
          v-if="!versions?.rollouts?.length"
          description="暂无发布计划"
        />

        <div v-else class="rollouts-list">
          <a-card
            v-for="rollout in versions.rollouts"
            :key="rollout.id"
            class="rollout-card"
            size="small"
          >
            <template #title>
              <div class="rollout-title">
                <span>{{ rollout.name }}</span>
                <a-tag
                  :color="getRolloutStatusColor(rollout.status)"
                  size="small"
                >
                  {{ getRolloutStatusLabel(rollout.status) }}
                </a-tag>
              </div>
            </template>

            <div class="rollout-info">
              <p><strong>目标版本:</strong> {{ rollout.targetVersion }}</p>
              <p>
                <strong>策略:</strong>
                {{ getRolloutStrategyLabel(rollout.strategy) }}
              </p>
              <p><strong>进度:</strong> {{ rollout.progress || 0 }}%</p>
              <p v-if="rollout.scheduledAt">
                <strong>计划时间:</strong> {{ formatDate(rollout.scheduledAt) }}
              </p>
            </div>

            <div class="rollout-actions">
              <a-button
                v-if="rollout.status === 'PENDING'"
                type="link"
                size="small"
                @click="executeRollout(rollout)"
              >
                执行
              </a-button>
              <a-button
                v-if="rollout.status === 'IN_PROGRESS'"
                type="link"
                size="small"
                @click="pauseRollout(rollout)"
              >
                暂停
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="viewRolloutDetail(rollout)"
              >
                详情
              </a-button>
              <a-popconfirm
                title="确定要删除这个发布计划吗？"
                @confirm="deleteRollout(rollout.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 创建版本模态框 -->
    <a-modal
      v-model:open="createVersionModalVisible"
      title="创建新版本"
      @ok="createVersion"
      @cancel="cancelCreateVersion"
    >
      <a-form :model="versionForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="版本号" name="version">
              <a-input
                v-model:value="versionForm.version"
                placeholder="请输入版本号（如：v1.2.3）"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="版本类型" name="type">
              <a-select
                v-model:value="versionForm.type"
                placeholder="请选择版本类型"
              >
                <a-select-option value="MAJOR">主版本</a-select-option>
                <a-select-option value="MINOR">次版本</a-select-option>
                <a-select-option value="PATCH">补丁版本</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="变更说明" name="changelog">
          <a-textarea
            v-model:value="versionForm.changelog"
            placeholder="请输入变更说明"
            :rows="4"
          />
        </a-form-item>

        <a-form-item label="发布说明" name="releaseNotes">
          <a-textarea
            v-model:value="versionForm.releaseNotes"
            placeholder="请输入发布说明（可选）"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="versionForm.tags"
            mode="tags"
            placeholder="请输入标签"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 发布计划模态框 -->
    <a-modal
      v-model:open="rolloutModalVisible"
      title="创建发布计划"
      width="800px"
      @ok="createRollout"
      @cancel="cancelCreateRollout"
    >
      <a-form :model="rolloutForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="计划名称" name="name">
              <a-input
                v-model:value="rolloutForm.name"
                placeholder="请输入计划名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标版本" name="targetVersion">
              <a-select
                v-model:value="rolloutForm.targetVersion"
                placeholder="请选择目标版本"
              >
                <a-select-option
                  v-for="version in availableVersions"
                  :key="version.version"
                  :value="version.version"
                >
                  {{ version.version }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="发布策略" name="strategy">
              <a-select
                v-model:value="rolloutForm.strategy"
                placeholder="请选择发布策略"
              >
                <a-select-option value="ALL_AT_ONCE">全量发布</a-select-option>
                <a-select-option value="CANARY">金丝雀发布</a-select-option>
                <a-select-option value="BLUE_GREEN">蓝绿发布</a-select-option>
                <a-select-option value="ROLLING">滚动发布</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="计划时间" name="scheduledAt">
              <a-date-picker
                v-model:value="rolloutForm.scheduledAt"
                show-time
                placeholder="请选择计划时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 策略配置 -->
        <a-form-item label="策略配置" name="config">
          <div class="strategy-config">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="批次数量" name="batchCount">
                  <a-input-number
                    v-model:value="rolloutForm.config.batchCount"
                    :min="1"
                    :max="10"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="批次间隔（分钟）" name="batchInterval">
                  <a-input-number
                    v-model:value="rolloutForm.config.batchInterval"
                    :min="1"
                    :max="1440"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="健康检查超时（秒）"
                  name="healthCheckTimeout"
                >
                  <a-input-number
                    v-model:value="rolloutForm.config.healthCheckTimeout"
                    :min="10"
                    :max="300"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </a-form-item>

        <a-form-item label="发布说明" name="description">
          <a-textarea
            v-model:value="rolloutForm.description"
            placeholder="请输入发布说明"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 版本详情模态框 -->
    <a-modal
      v-model:open="versionDetailModalVisible"
      title="版本详情"
      width="600px"
      :footer="null"
    >
      <div v-if="selectedVersion" class="version-detail">
        <a-descriptions title="基本信息" :column="2">
          <a-descriptions-item label="版本号">
            {{ selectedVersion.version }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getVersionStatusColor(selectedVersion.status)">
              {{ getVersionStatusLabel(selectedVersion.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDate(selectedVersion.createdAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="创建人">
            {{ selectedVersion.createdBy }}
          </a-descriptions-item>
          <a-descriptions-item
            v-if="selectedVersion.releasedAt"
            label="发布时间"
          >
            {{ formatDate(selectedVersion.releasedAt) }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider />

        <a-descriptions title="变更内容" :column="1">
          <a-descriptions-item label="变更说明">
            {{ selectedVersion.changelog }}
          </a-descriptions-item>
          <a-descriptions-item
            v-if="selectedVersion.releaseNotes"
            label="发布说明"
          >
            {{ selectedVersion.releaseNotes }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider v-if="selectedVersion.tags?.length" />

        <a-descriptions
          v-if="selectedVersion.tags?.length"
          title="标签"
          :column="1"
        >
          <a-descriptions-item label="标签列表">
            <a-tag
              v-for="tag in selectedVersion.tags"
              :key="tag"
              color="blue"
              style="margin: 2px"
            >
              {{ tag }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-versions {
  .versions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
    }
  }

  .version-card {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .versions-section {
    .versions-list {
      .version-item {
        .version-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          h4 {
            margin: 0;
            color: #1890ff;
          }
        }

        .version-info {
          p {
            margin: 4px 0;
            font-size: 12px;
          }
        }
      }
    }
  }

  .rollout-section {
    .rollouts-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 12px;
    }

    .rollout-card {
      .rollout-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .rollout-info {
        margin-bottom: 8px;

        p {
          margin: 4px 0;
          font-size: 12px;
        }
      }

      .rollout-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .strategy-config {
    padding: 12px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    background: #fafafa;
  }

  .version-detail {
    .ant-tag {
      margin: 2px;
    }
  }
}
</style>
